import 'package:easydouban/bean/i_search_entity.dart';
import 'package:easydouban/provider/search_provider.dart';
import 'package:easydouban/sql/dao/search_dao.dart';
import 'package:easydouban/sql/exe/search_sql.dart';
import 'package:easydouban/tools/circularTool.dart';
import 'package:easydouban/tools/toastTool.dart';
import 'package:easydouban/ui/search_result.dart';
import 'package:easydouban/viewModel/future_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../bean/i_top_entity.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({Key? key}) : super(key: key);

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage>{
  final TextEditingController _searchController = TextEditingController();
  final FocusNode _searchNode = FocusNode();
  final _formKey = GlobalKey<FormState>();

  String _searchContent = '';
  String _lastSearch = '';
  bool _isShowClear = false;
  late Widget? defaultContent;

  @override
  void initState() {
    super.initState();
    _searchController.addListener(() {
      if(_searchController.text.isEmpty){
        _isShowClear = false;
        defaultContent = _buildHistory();
      }else{
        _isShowClear = true;
        _searchContent = _searchController.text.toString();
        defaultContent = _buildSearchListView(_searchContent);
      }
      setState(() {});
    });

    ///初始化默认显示内容
    defaultContent = _buildHistory();
    _loadSearchList();
  }

  Future _loadSearchList() async{
    await SearchDao.getInstance().queryAll().then((value) {
        final provider = context.read<SearchProvider>();
        if(value != null){
          provider.searchList = value;
        }
    });
  }

  Widget _buildSearchListView(String key) {
    if(key.isNotEmpty && key == _lastSearch){
      return defaultContent!;
    }else{
      _lastSearch = key;
    }

    ///模糊搜索列表，添加富文本高亮显示
    Widget displayContent = const Center(child: CircularProgressIndicator());
    List<ITopEntity> resultList = [];
    getSearchList(key)
        .then((value) => {
          if(value != null){
            resultList = value
          }})
        .catchError(
            (e) => {displayContent = const Center(child: Text('加载失败!'))})
        .whenComplete(() => {
              displayContent = ListView.builder(
                  itemCount: resultList.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      leading: const Icon(Icons.search, size: 20),
                      title: Transform(
                        transform: Matrix4.translationValues(-16, 0.0, 0.0),
                        child: RichText(
                          overflow: TextOverflow.ellipsis,
                          text: TextSpan(
                              text: resultList[index].data[0].name.substring(0, key.length),
                              style: const TextStyle(
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold),
                              children: [
                                TextSpan(
                                  text: resultList[index].data[0].name.substring(key.length),
                                  style: const TextStyle(color: Colors.grey),
                                )
                              ]),
                        ),
                      ),
                      onTap: () {
                        exeSearchInsert(SearchRecord(resultList[index].data[0].name.toString()), context);
                        Navigator.of(context).push(MaterialPageRoute(builder: (context) => SearchResultPage(resultList[index].data[0].name)));
                      },
                    );
                  }),
              setState(() {
                if (resultList.isEmpty) {
                  displayContent = const Center(child: Text('没有搜索到相关内容!'));
                }else{
                  defaultContent = displayContent;
                }
              }),
            });
    return displayContent;
  }

  ///历史记录删除按钮和历史记录列表
  Widget _buildHistory(){
    return Column(
          children: [
            GestureDetector(
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    getText('历史记录',color: Colors.black,textSize: 16.0,fontWeight: FontWeight.bold),
                    const Icon(Icons.delete_forever,color: Colors.grey)
                  ]
              ),
              onTap: (){
                ///清空搜索记录
                exeSearchClear(context);
              },
            ),
            Flexible(child: _buildHistoryList())
          ],
        );
  }

  ///构建搜索记录List列表
  Widget _buildHistoryList() {
    return Container(
      margin: const EdgeInsets.only(top: 10.0),
      child: Consumer<SearchProvider>(
          builder: (ctx, searchProvider, child) {
            return GridView.builder(
                itemCount: searchProvider.searchList.length,
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4,
                    mainAxisSpacing: 10,
                    crossAxisSpacing: 10,
                    childAspectRatio: 3),
                itemBuilder: (ctx, index) {
                  return _buildHistoryItem(searchProvider.searchList[index].searchKey);
                });
          }),
    );
  }

  ///搜索记录item
  Widget _buildHistoryItem(String key){
    return GestureDetector(
      child: Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.all(5.0),
        decoration: const BoxDecoration(
            color: Colors.grey,
            borderRadius: BorderRadius.all(Radius.circular(10.0))
        ),
        child: getText(key,color: Colors.white),
      ),
      onTap: (){
        exeSearchInsert(SearchRecord(key),context);
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => SearchResultPage(key)));
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    ///搜索框
    Widget searchContent = Form(
        key: _formKey,
        child: TextFormField(
          textAlign: TextAlign.start,
          maxLines: 1,
          controller: _searchController,
          focusNode: _searchNode,
          style: const TextStyle(fontSize: 15.0,color: Colors.black),
          decoration: InputDecoration(
            icon: const Icon(Icons.search,color: Colors.grey,size: 25),
            hintText: '输入搜索内容',
            hintStyle: const TextStyle(fontSize: 15.0,color: Colors.grey),
            border: InputBorder.none,
            suffixIcon: (_isShowClear) ? IconButton(
                onPressed: (){
                  _searchController.clear();
                  _searchContent = '';
                  },
                icon: const Icon(Icons.clear,color: Colors.grey,size: 25)) : null
          ),
          validator: (value){
            if(value == null || value.isEmpty){
              showFailedToast('搜索内容不能为空!');
            }
            return null;
          },
          onChanged: (value){
            _searchContent = value.toString();
          },
          onSaved: (String? value){
            _searchContent = value.toString();
          },
        )
    );

    ///搜索条
    Widget searchBox = Container(
      height: 50.0,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 10,right: 10),
      decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(20.0)),
          color: Colors.black12
      ),
      child: searchContent,
    );

    ///搜索栏
    Widget searchBar = Row(
      children: [
        Expanded(flex:1,child: searchBox),
        TextButton(
            onPressed: (){
              if(_searchContent.isEmpty || _searchContent.length == 0){
                showFailedToast('搜索内容不能为空!');
              }else{
                exeSearchInsert(SearchRecord(_searchContent.toString()), context);
                Navigator.of(context).push(MaterialPageRoute(builder: (context) => SearchResultPage(_searchContent.toString())));
              }
            },
            child: getText('搜索',color: Colors.green,textSize: 16,fontWeight: FontWeight.bold))
      ],
    );


    return Container(
      margin: const EdgeInsets.only(left: 15.0,right: 15.0,top: 20.0),
      child: Column(
        children: [
          searchBar,
          const SizedBox(height: 20.0),
          Expanded(child: defaultContent!)
        ],
      ),
    );
  }
}

// class SearchBarDelegate extends SearchDelegate<String>{
//   ///右侧内容，一般放清空按钮
//   @override
//   List<Widget>? buildActions(BuildContext context) {
//    return [
//      IconButton(
//        onPressed: (){},
//        icon: const Icon(Icons.clear,color: Colors.grey))
//    ];
//   }
//
//   ///左侧内容，一般放返回按钮
//   @override
//   Widget? buildLeading(BuildContext context) {
//     return null;
//   }
//
//   ///搜索内容
//   @override
//   Widget buildResults(BuildContext context) {
//    return Center(
//      child: Text(query),
//    );
//   }
//
//   ///搜索列表
//   @override
//   Widget buildSuggestions(BuildContext context) {
//     final resultList = query.isEmpty ? suggestionList :
//     searchList.where((element) => element.startsWith(query)).toList();
//
//     return ListView.builder(
//         itemCount: resultList.length,
//         itemBuilder: (context,index){
//           return ListTile(
//             leading: const Icon(Icons.search,size: 20),
//             title: Transform(
//               transform: Matrix4.translationValues(-16, 0.0, 0.0),
//               child: RichText(
//                 text: TextSpan(
//                     text: resultList[index].substring(0,query.length),
//                     style: const TextStyle(
//                         color: Colors.black,fontWeight: FontWeight.bold
//                     ),
//                     children: [
//                       TextSpan(
//                         text: resultList[index].substring(query.length),
//                         style: const TextStyle(
//                             color: Colors.grey
//                         ),
//                       )
//                     ]
//                 ),
//               ),
//             ),
//             onTap: (){},
//           );
//         }
//     );
//   }
//
// }

const suggestionList = [
  "肖申克的救赎",
  "教父",
  "蝙蝠侠：黑暗骑士",
  "教父2",
  "十二怒汉",
  "辛德勒的名单",
  "指环王3：王者无敌"
];
